<?php

namespace App\Http\Controllers\Api;

use App\Models\Users;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    /**
     * 获取微信次奥程序接口调用凭证
     * @return array
     * @throws GuzzleException
     */
    public function getAccessToken(): array
    {
        $appid = config('mbcore_mcore.weapp.appid','');
        $secret = config('mbcore_mcore.weapp.secret','');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid='.$appid.'&secret='.$secret.'&grant_type=client_credential';
        $response = GuzzleHttpGet($url);
        if($response['errcode'] !=0){
            return retError([
                'msg'=>$response['errcode'].'--'.$response['errmsg'],
            ]);
        }
        return ret([
            'access_token'=>$response['access_token'],
            'expires_in'=>$response['expires_in'],
        ]);
    }
    /**
     * 小程序登录
     * @return array
     * @throws GuzzleException
     */
    public function wxLogin(): array
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $appid = config('mbcore_mcore.weapp.appid','');
        $secret = config('mbcore_mcore.weapp.secret','');
        $js_code = \request('code','bearer');
        if(!$js_code){
            return retError([
                'msg'=>'缺少code!'
            ]);
        }
        $grant_type = 'authorization_code';
        $url .= '?appid='.$appid.'&secret='.$secret.'&js_code='.$js_code.'&grant_type='.$grant_type;
        $response = GuzzleHttpGet($url);

        if(!empty($response['errcode']) ){
            return retError([
                'msg'=>$response['errcode'].'--'.$response['errmsg'],
            ]);
        }
        $openid = $response['openid'];
        $unionid = empty($response['unionid']) ? '' : $response['unionid'];
        $where = [
            'openid'=>$openid
        ];
        $user = Users::query()->where($where)->first();
        $is_register = false;
        $token_data = '';
        if(!$user){
            Users::query()->create([
                'openid'=>$openid,
                'unionid'=>$unionid,
//                'session_key'=>$response['session_key']
            ]);

            $user = Users::query()->where($where)->first();
            $user_data = Users::getDataByID($user['id']);
            $columns = ['id','mobile','password','openid'];
            $data = Users::query()->where($where)->first($columns);
            $token = JWTAuth::fromUser($data);
            if (!$token) {
                return retError([
                    'msg'=>'登录授权错误，请重新登录',
                ],401);
            }
            $token_data = RespondWithToken($token);

        }else{
            $name = $user['name'];
            if($name){
                $is_register = true;
            }
            $user_data = Users::getDataByID($user['id']);
            $columns = ['id','mobile','password','openid'];
            $data = Users::query()->where($where)->first($columns);
            $token = JWTAuth::fromUser($data);
            if (!$token) {
                return retError([
                    'msg'=>'登录授权错误，请重新登录',
                ],401);
            }
            $token_data = RespondWithToken($token);
//            $user_id = $data->id;
        }
        return [
            'is_register'=>$is_register,
            'user_data'=>$user_data,
            'token'=>$token_data
        ];
    }

    /**
     * 登录接口
     * @return array
     */
    public function login(): array
    {
//        return \request()->all();
        #账号都是手机号
        $mobile = request('mobile',null);
        if(!$mobile){
            return retError([
                'msg'=>'手机号不能为空!'
            ]);
        }else{
            $vp = VerifyMobile($mobile,true);
            if($vp['code'] == 0){
                return retError([
                    'msg'=>$vp['msg_zh']
                ]);
            }
        }
        $where = [
            'mobile'=>$mobile
        ];
        $columns = ['id','mobile','password'];
        $data = Users::query()->where($where)->first($columns);

        if(!$data){
            return retError([
                'msg'=>'该手机号未注册，请先注册'
            ]);
        }
//        $data->toArray();
        #验证码或密码登录
        $code = \request('code',null);
        if($code){
            #验证登录
            #验证短信验证码是否正确
            $md5 = 'SMS'.$mobile.'-smscode';
//            $cacheKey = 'getSMSCode'.':' . md5($md5);
//            SmsCodeVetify($cacheKey);
//            Cache::forget($cacheKey);
            $token = JWTAuth::fromUser($data);
            if (!$token) {
                return retError([
                    'msg'=>'登录错误，请重新登录',
                ],401);
            }
            $user_id = $data->id;
        }else{
            #密码登录
            $password = request('password');
            if(!$password){
                return retError([
                    'msg'=>'请输入登录密码',
                ],201);
            }
            $credentials = request(['mobile', 'password']);
            $token = auth('api')->attempt($credentials);
            if (!$token) {
                return retError([
                    'msg'=>'密码错误，请重新输入',
                ],401);
            }
            $user_id = auth('api')->id();
        }
        $users = Users::getDataByID($user_id);
        $result = [
            'users'=>$users,
            'token'=>RespondWithToken($token),
        ];
        return ret([
            'data'=>$result,
        ]);
    }

    /**
     * 用户注册
     * @param Request $request
     * @return array
     */
    public function register(Request $request): array
    {
        $user_id = auth('api')->id();
        $table = 'user_register';
        #表单验证
        # 姓名-name、在校经历（学历）-degree，在校时间-school_time，所在学院-college，专业-major，当前坐在地-habitation和当前职业-career
        #【工作单位-workplace，所属行业-profession，职务-post】
//        $validator = FormVerify($table, $request);
//        if ($validator['code'] == 201) {
//            return retError($validator['msg']);
//        }
        $key = [
            'name','degree','school_time','college','major','habitation',
            'career','workplace','profession','post','openid','email','username','mobile','password'
            ,'work_location','wechat','post','profession','workplace','career'
        ];
        $update = $request->only($key);

        if (!empty($update['password'])) {
            $update['password'] = bcrypt($update['password']);
        }
        $usernameId = 0;
        if (!empty($update['username'])) {
           // $usernameId=Users::query()->where('username','=', $update['username'])->value('id');
        }
        $mobileId = 0;
        if (!empty($update['mobile'])) {
            $mobileId=Users::query()->where('mobile','=', $update['mobile'])->value('id');
        }
        $emailId = 0;
        if (!empty($update['email'])) {
            $emailId=Users::query()->where('email','=', $update['email'])->value('id');
        }

        if ($usernameId>0 || $mobileId>0 || $emailId>0) {
            return retError([
                'msg'=>'用户已存在',
            ],401);
        }

        //由于wxlog登录 openid 已注册    本次通过openid 去修改用户信息
        $openid = 0;
        if (!empty($update['openid'])) {
            $openid =Users::query()->where('openid','=', $update['openid'])->value('id');
        }

        DB::beginTransaction();
        try {
            Log::info($update);
            if($openid > 0 ){
                //修改
                Users::query()->where('id',$openid)->update($update);
            }else{
                //添加
                Users::query()->insert($update);
            }
            DB::commit();
            return ret('注册成功');
        } catch (\Exception $exception) {
            DB::rollback();
            return retError($exception->getMessage(),$request);
        }
//        return response()->json(auth('api')->user());
    }

    /**
     * 退出登录
     *
     * @return array
     */
    public function logout(): array
    {
        auth('api')->logout();
        return ret('登出成功');
//        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     *  Refresh a token.
     *  刷新token，如果开启黑名单，以前的token便会失效。
     *  值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return array
     */
    public function refreshToken(): array
    {
        $token = auth('api')->refresh();
        $refreshToken = RespondWithToken($token);
        return ret([
            'data'=>$refreshToken,
        ]);;
    }

    /**
     *
     * 判断用户是否注册
     *
     * @return array
     */
    public function whetherToRegister(): array
    {
        $user_id = auth('api')->id();
        $name = Users::query()->where('id',$user_id)->value('name');
        $is_register = false;
        if($name){
            $is_register = true;
        }
        return ret([
            'is_register'=>$is_register,
        ]);
    }
}
